package com.atguigu.study.service.impl;

import com.atguigu.study.annotations.MyRedisCache;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.study.entities.User;
import com.atguigu.study.service.UserService;
import com.atguigu.study.mapper.UserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
* @author 胡hu
* @description 针对表【t_user(用户表)】的数据库操作Service实现
* @createDate 2025-07-31 13:33:58
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    private static final String CACHE_KEY_USER="user:";
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private UserMapper userMapper;
    @Override
    public boolean save(User user) {
        boolean revaule=false;
        log.info("插入之前:"+user);
        revaule=super.save(user);
        log.info("插入之后："+user);
        log.info("--------------");
        if (!revaule) {
            this.userMapper.selectById(user.getId());
            String key=CACHE_KEY_USER+user.getId();
            redisTemplate.opsForValue().set(key,user);
        }
        return revaule;
    }

//    @Override
//    public User getById(Serializable id) {
//        User user=null;
//        String key=CACHE_KEY_USER+id;
//        user=(User)redisTemplate.opsForValue().get(key);
//        if (user == null)
//        {
//            //从mysql查出来user
//            user = this.userMapper.selectById(id);
//
//            //3 mysql有，redis无
//            if (user != null)
//            {
//                //把mysql捞到的数据写入redis，方便下次查询能redis命中。
//                redisTemplate.opsForValue().set(key, user);
//            }
//        }
//        return user;
//    }

    @Override
    @MyRedisCache(keyPrefix = "user",matchValue = "#id")
    public User getById(Serializable id) {
        return this.userMapper.selectById(id);
    }
}




